auth.js ➔ loggedIn   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
import storage from "./storage";
2
const auth = {
3
  loggedIn: function loggedIn() {
4
    const token = storage.readToken();
5
    const Hours = 1000 * 60 * 60;
6
    const notExpired = new Date().getTime() - token.date < Hours;
7
    return token && notExpired;
8
  },
9
10
  login: async function login(email, password) {
11
    const data = {
12
      email: email,
13
      password: password,
14
      api_key: process.env.REACT_APP_REST_API_KEY,
15
    };
16
    const tokenObj = storage.readToken();
17
    const response = await fetch(
18
      `${process.env.REACT_APP_API_URL}/auth/login/server/admin`,
19
      {
20
        method: "POST",
21
        body: JSON.stringify(data),
22
        headers: {
23
          "content-type": "application/json",
24
          "x-access-token": tokenObj.token,
25
        },
26
      }
27
    );
28
    const result = await response.json();
29
30
    if (Object.prototype.hasOwnProperty.call(result, "errors")) {
31
      return {
32
        message: result.errors.title,
33
        description: result.errors.detail,
34
        type: "danger",
35
      };
36
    }
37
38
    storage.storeToken(result.data.token);
39
40
    return {
41
      message: "Success",
42
      description: result.data.message,
43
      type: "success",
44
    };
45
  },
46
  logout: async function logout() {
47
    storage.deleteToken();
48
  },
49
};
50
51
export { auth };
52